import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Select, Spin} from 'antd';

const Option = Select.Option;
class MultipleSelect extends PureComponent {
    state = {
        isFetching: false,
        sdataOptions: []
    }
    onBlur = data => {
        this.setState({
            sdataOptions: this.props.dataOptions,
            value: data,
            isFetching: false
        });
        if(this.props.onBlur)
            this.props.onBlur(data.map(v => v.key), this.props.name);
    }
    onChange = svalue => {
        this.setState({
            sdataOptions: this.props.dataOptions,
            svalue,
            isFetching: false
        });
    }
    onSearch = value => {
        this.setState({
            sdataOptions: this.props.dataOptions.filter(v => v.code.includes(value)),
            isFetching: false
        });
    }
    render() {
        const {placeholder, dropdownMatchSelectWidth, allowClear, dataOptions, value} = this.props;
        const {svalue, isFetching, sdataOptions} = this.state;
        const pvalue = value && value.map(v => ({
            key: v
        }));
        let options = [];
        if(sdataOptions.length > 0)
            options = sdataOptions;
        else options = dataOptions;
        const children = [];
        options.forEach(o => children.push(<Option key={o.code} value={o.code}>{o.code}</Option>));
        return (
            <Select
                allowClear={allowClear}
                mode="multiple"
                showSearch
                labelInValue
                value={svalue || pvalue}
                placeholder={placeholder}
                dropdownMatchSelectWidth={dropdownMatchSelectWidth}
                notFoundContent={isFetching ? <Spin size="small" /> : null}
                filterOption={false}
                onSearch={this.onSearch}
                onChange={this.onChange}
                onBlur={this.onBlur}>
                {
                    children
                }
            </Select>
        );
    }
}

MultipleSelect.propTypes = {
    // 是否允许清空，默认false
    allowClear: PropTypes.bool,
    //下拉数据
    dataOptions: PropTypes.array,
    /**
     * 下拉菜单和选择器同宽 默认 false
     */
    dropdownMatchSelectWidth: PropTypes.bool,
    /**
     * 默认为id
     */
    keyIndex: PropTypes.string,
    name: PropTypes.string,
    placeholder: PropTypes.string,
    /**
     * 结构和异步请求返回的数据的保持一致
     */
    value: PropTypes.array,
    onBlur: PropTypes.func,
    onChange: PropTypes.func,
};

MultipleSelect.defaultProps = {
    keyIndex: 'id',
    dropdownMatchSelectWidth: false,
    allowClear: true
};

export default MultipleSelect;
